import warnings

import pandas as pd
from sklearn import preprocessing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeRegressor

warnings.filterwarnings('ignore')
# 1.编写一个Python文件，实现功能：使用os打开purchase.txt文件，
# 并通过python代码解决purchase.txt文件的中文乱码，使其正常显示。
opener = open('purchase.txt','r',encoding='gbk')
lines = opener.readlines()
print(lines)
# 2.使用Python代码，在当前目录下创建student/yuekao目录，将purchase.txt文件复制到yuekao下，重命名为test.txt。
writer = open('student/yuekao/test.txt','w')
writer.writelines(lines)
writer.close()
# 3.编写一个函数remove_any，接受一个目录名作为参数，删除该目录及下面所有子目录和文件。
# 4、对《手机销售分布分析.CSV》，计算样本特征的相关性，基本信息
df = pd.read_csv('wuhu.csv')
X = df.drop(['price', 'start_time'],axis=1)
le = preprocessing.LabelEncoder()
for i in ['type','brand','sex','province']:
    X[i] = le.fit_transform(X[i])
print(X.corr())
print(X.info())
# 5、对《手机销售分布分析.CSV》，拆分测试集和训练接，随机洗牌。
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42,shuffle=True)
# 6、自主在sklearn中选择两种合适的算法，对用户下单行为进行数据建模，使用网格调优
#决策树
tree = DecisionTreeRegressor(random_state=0)
#网格搜索
parameters1 = {'min_samples_split':(1, 2, 3), 'max_depth':[100, 200, 300], 'min_samples_leaf':[1, 2, 3]}
treeClf = GridSearchCV(tree, parameters1)
treeClf.fit(X_train, y_train)
best_tree_model = treeClf.best_estimator_
tree_score = treeClf.best_score_

#随机森林
rf =  RandomForestRegressor(max_depth=2, random_state=0)
#网格搜索
rfClf = GridSearchCV(tree, parameters1)
rfClf.fit(X_train, y_train)
best_rf_model = rfClf.best_estimator_
rf_score = rfClf.best_score_
# 7、使用最佳模型预测样本数据，并将结果保存CSV
if tree_score > rf_score:
    print('决策树的评分高')
    y_pred = best_tree_model.predict(X_test)
else:
    print('随机森林的评分高')
    y_pred = best_rf_model.predict(X_test)
print(y_pred)
pd.DataFrame(y_pred, columns=['price']).to_csv('迪迦.csv',index=False)